package com.bifrost.repository;

import com.bifrost.entity.Media;
import com.bifrost.entity.ProductSku;
import com.bifrost.entity.SkuMediaMap;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Collection;
import java.util.List;

/**
 * @author rangjf
 * @date 2017/11/2
 */
public interface SkuMediaMapRepository extends JpaRepository<SkuMediaMap, Long> {

    /**
     * 查询sku所有图片信息
     *
     * @param sku
     * @return
     */
    List<SkuMediaMap> findAllByProductSku(ProductSku sku);

    /**
     * 用原生sql查询所有素材
     *
     * @param skuId
     * @return
     */
    @Query(value = "SELECT  * FROM  SKU_MEDIA_MAP M WHERE SKU_ID =?1 ", nativeQuery = true)
    List<SkuMediaMap> findAllByProductSku(Long skuId);

    /**
     * 查询sku指定类型的素材按序号升序排列
     *
     * @param sku
     * @param key
     * @return
     */
    List<SkuMediaMap> findAllByProductSkuAndMapKeyOrderBySortOrderAsc(ProductSku sku, String key);

    /**
     * 用原生sql查询sku的medias
     *
     * @param skuId id
     * @param key   类型
     * @return
     */
    @Query(value = "SELECT  * FROM  SKU_MEDIA_MAP M WHERE SKU_ID =?1 AND MAP_KEY =?2 ", nativeQuery = true)
    List<SkuMediaMap> findAllByProductSkuAndMapKeyOrderBySortOrderAsc(Long skuId, String key);

    /***
     *  根据sku 删除图片
     *@param sku
     */
    @Modifying
    void deleteAllByProductSku(ProductSku sku);

    /***
     *  根据sku 删除图片
     *@param sku
     */
    @Modifying
    void deleteAllByProductSkuAndMapKeyEquals(ProductSku sku,String key);


    List<SkuMediaMap> findAllByProductSkuAndMapKeyEquals(ProductSku sku , String key);

    @Modifying
    @Query(nativeQuery = true, value = "DELETE FROM sku_media_map WHERE sku_media_map.SKU_ID=?1 and sku_media_map.map_key=?2")
    int deleteSkuMediaMap(Long skuId, String mapKey);

    @Modifying
    @Query(nativeQuery = true, value = "DELETE FROM sku_media_map WHERE sku_media_map.SKU_ID=?1 and sku_media_map.map_key=?2 AND sku_media_map.media_id not in (?3)")
    int deleteMapNotIn(Long sku, String mapKey , List<Long> medias);
}
